package com.readfeed.app;

import com.readfeed.app.fragment.PrefsFragment;

import android.os.Bundle;
import android.preference.ListPreference;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.app.NavUtils;

public class PreferencesActivity extends Activity implements OnSharedPreferenceChangeListener{

	public static final String UPDATE_ITEMS_PREF_KEY = "pref_updatePeriod";
	public static final String DISCARD_ITEMS_PREF_KEY = "pref_discardPeriod";
	private PrefsFragment mPrefFragment;	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_preferences);
		setupActionBar();				
		mPrefFragment = new PrefsFragment();
		
		getFragmentManager().beginTransaction().replace(android.R.id.content, mPrefFragment).commit();
	}
	
	@Override
	protected void onResume() {		
		super.onRestart();
		
		mPrefFragment.getPreferenceScreen().getSharedPreferences()
        .registerOnSharedPreferenceChangeListener(this);
	}
	
	@Override
	protected void onPause() { 
		super.onPause();
		
		mPrefFragment.getPreferenceScreen().getSharedPreferences()
        .unregisterOnSharedPreferenceChangeListener(this);
	}

	/**
	 * Set up the {@link android.app.ActionBar}.
	 */
	private void setupActionBar() {

		getActionBar().setDisplayHomeAsUpEnabled(true);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.preferences, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
			String key) {
		if (key.equals(UPDATE_ITEMS_PREF_KEY)) {
			ListPreference pref = (ListPreference)mPrefFragment.findPreference(key);
			CharSequence entryText = pref.getEntry();
			pref.setSummary(entryText);			
		}
		
		if (key.equals(DISCARD_ITEMS_PREF_KEY)) {
			ListPreference pref = (ListPreference) mPrefFragment.findPreference(key);
			CharSequence entryText = pref.getEntry();
			pref.setSummary(entryText);
		}		
	}
}
